<?php

class MenuController extends AdminController{
	
	public $parentUrl;

	public function init(){
		parent::init();
		$this->parentUrl = $this->module->id .'/' . Yii::app()->getController()->getId();
	}

	public function actionIndex(){
		try{
			$model = Menu::model()->findAll();
			$this->render('index',array(
				'data' => $model,
				'parentUrl' => $this->parentUrl
				));
		}catch(Exception $e){
			Yii::log("Invalid request(Language). Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
		}
	}

	public function actionCreate(){
		try{
			$model= new Menu();
			if(isset($_POST['Menu'])){
				$model->attributes = $_POST['Menu'];
				$model->is_static = isset($_POST['Menu']['is_static']) ? 1 : 0;
				$model->validate();
				if(!$model->hasErrors()){
					if($model->save()){
						$this->redirect(Yii::app()->createAbsoluteUrl('admin/menu'));
					}
				}
			}
			$this->render('create',array(
				'model' => $model,
				'parentUrl' => $this->parentUrl
				)); 
		}catch(Exception $e){
			Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
		}
	}


	public function actionUpdate($id){
		try{
			$model= $this->loadModel($id);
			if(isset($_POST['Menu'])){
				$model->attributes = $_POST['Menu'];
				$model->is_static = isset($_POST['Menu']['is_static']) ? 1 : 0;
				$model->validate();
				if(!$model->hasErrors()){
					if($model->save()){						
						$this->redirect(Yii::app()->createAbsoluteUrl('admin/menu'));
					}
				}
			}
			$this->render('update',array(
				'model' => $model,
				'parentUrl' => $this->parentUrl
				)); 
		}catch(Exception $e){
			Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
		}
	}

	public function actionDelete($id){	
		$model = $this->loadModel($id);	
		if($model){
			if($model->delete()){
				$this->redirect(Yii::app()->createAbsoluteUrl('admin/menu'));
			}
		}
	}

	public function loadModel($id){
		try{
			$model = Menu::model()->findByPk($id);
			if($model == null){
				throw new Exception(404, "The request does not exist");
			}
			return $model;
		}catch(Exception $e){
			Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
		}
	}
}